What Are the Different Events in JavaScript?

JavaScript events are actions or occurrences that happen in the browser. These events can be triggered by user interactions, browser activity, or JavaScript itself.

1. Mouse Events

Example:

        
document.getElementById("btn").addEventListener("click", () => {
    console.log("Button clicked!");
});
        
    

Output: Logs "Button clicked!" when the button is clicked.

2. Keyboard Events

Example:

        
document.addEventListener("keydown", (event) => {
    console.log("Key pressed:", event.key);
});
        
    

Output: Logs the key pressed.

3. Form Events

Example:

        
document.getElementById("form").addEventListener("submit", (event) => {
    event.preventDefault(); // Prevent form submission
    console.log("Form submitted!");
});
        
    

Output: Logs "Form submitted!" on form submission.

4. Window Events

Example:

        
window.addEventListener("resize", () => {
    console.log("Window resized!");
});
        
    

Output: Logs "Window resized!" on window resize.

Summary:

Event Type Description Examples
Mouse Events Triggered by mouse actions. click, mouseover
Keyboard Events Triggered by keyboard input. keydown, keyup
Form Events Triggered by form interactions. submit, change
Window Events Triggered by browser window actions. resize, scroll